package com.demo.test;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class Demo {
	public static void main(String[] args) throws InterruptedException {
        CyclicBarrier cyclicBarrier=new CyclicBarrier(3);
        
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
//                    Thread.sleep(new java.util.Random().nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());

                // 冲破栅栏代表A线程结束
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                    throw new RuntimeException("cylicBarrier.await()拋出異常：",e);
                }
            }
        }, "Thread-A");

        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
//                    Thread.sleep(new java.util.Random().nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());
                
                // 冲破栅栏代表B线程结束
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                    throw new RuntimeException("cylicBarrier.await()拋出異常：",e);
                }
            }
        }, "Thread-B");

        Thread threadC = new Thread(new Runnable() {
            @Override
            public void run() {
                // 等待前两个(A/B)线程结束，只有前两个(A/B)线程结束了才能满足3个线程都冲破栅栏，
                try {
                    // 等待栅栏被冲破，冲破栅栏的条件是：A/B/C三个线程都到达await()。
                    // 只有栅栏冲破，才能向下执行，否则先到达的线程等待。
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                    throw new RuntimeException("cylicBarrier.await()拋出異常：",e);
                }
                // 满足了三个线程都冲破栅栏才向下执行
                System.out.println(Thread.currentThread().getName());
            }
        }, "Thread-C");
        
        threadA.start();
        threadB.start();
        threadC.start();        
    }

}
